package com.wlxk.message.core.service.impl;

import cn.hutool.extra.mail.MailUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.wlxk.base.common.util.WlPreconditions;
import com.wlxk.core.tool.WlEmptyUtil;
import com.wlxk.message.client.dto.MailTemplateDTO;
import com.wlxk.message.client.dto.SendMailDTO;
import com.wlxk.message.core.service.MailService;
import com.wlxk.message.core.service.MailTemplateService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Map;

/**
 * @author ：wlxk
 * @since ：2022/2/8 13:34
 */
@Slf4j
@Service
public class MailServiceImpl implements MailService {

    @Autowired
    private MailTemplateService mailTemplateService;

    @Override
    public Boolean sendMail(SendMailDTO sendMailDTO) {
        MailTemplateDTO templateDTO = mailTemplateService.queryByCode(sendMailDTO.getTemplateCode());
        if (null == templateDTO) {
            WlPreconditions.checkNotEmpty(sendMailDTO.getRecipients(), "收件人不存在");
            MailUtil.sendText(sendMailDTO.getRecipients(), sendMailDTO.getSubject(), sendMailDTO.getContent());
            return true;
        }
        String subject = WlEmptyUtil.isNotEmpty(sendMailDTO.getSubject()) ? sendMailDTO.getSubject() : templateDTO.getSubject();
        String recipients = WlEmptyUtil.isNotEmpty(sendMailDTO.getRecipients()) ? sendMailDTO.getRecipients() : templateDTO.getRecipients();
        String ccRecipients = WlEmptyUtil.isNotEmpty(sendMailDTO.getCcRecipients()) ? sendMailDTO.getCcRecipients() : templateDTO.getCcRecipients();
        String content = templateDTO.getContent();
        if (WlEmptyUtil.isNotEmpty(sendMailDTO.getParams())) {
            JSONObject jsonObject = JSON.parseObject(sendMailDTO.getParams());
            for (Map.Entry<String, Object> entry : jsonObject.entrySet()) {
                String key = entry.getKey();
                Object valueObj = entry.getValue();
                String value = String.valueOf(valueObj);
                content = content.replaceAll("\\$\\{" + key + "}", value);
            }
        }
        String rsp = MailUtil.send(recipients, ccRecipients, null, subject, content, templateDTO.getIsHtml());
        log.info("sendMail rsp,{}", rsp);
        return true;
    }
}
